# -*- coding: utf-8 -*-
import json

from django.http import HttpResponse
from django.views.decorators.http import require_POST, require_GET

from common.channel.pay.kvpay import verify_draw_notify_sign as kvpay_notify, handler as kvpay_handler, \
    _get_api_key as kvpay_api_key
from common.channel.pay.mepay import verify_notify_sign as mepay_notify, handler as mepay_handler, \
    _get_api_key as mepay_api_key
from common.channel.pay.xlbpay import verify_draw_notify_sign as xlbpay_notify, handler as xlbpay_handler, \
    _get_api_key as xlbpay_api_key
from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)


@require_POST
def mepay_callback(request):
    data = json.loads(request.body)
    _LOGGER.info("mepay agent pay notify data: %s", data)
    mepay_notify(data, mepay_api_key(data.get('mch_id')))
    out_order_no = data['out_order_no']
    pay_status = data['pay_status']
    pay_fee = data['pay_fee']
    mepay_handler.agent_pay_notify(out_order_no, pay_status, pay_fee)

    return HttpResponse('success', status=200)


@require_GET
def kvpay_callback(request):
    data = dict(request.GET.iteritems())
    _LOGGER.info("kvpay agent pay notify data: %s", data)
    kvpay_notify(data, kvpay_api_key(data['MerchantNo']))
    out_order_no = data['OutTradeNo']
    if str(data['ResultCode']) == '0000':
        pay_status = 1
    pay_fee = data['Amount']
    kvpay_handler.agent_pay_notify(out_order_no, pay_status, pay_fee)

    return HttpResponse('SUCCESS', status=200)
           

@require_POST
def xlbpay_callback(request):
    body_list = request.body.replace("=", ":").split('&')
    body_dict = {}
    for i in body_list:
        body_dict[i.split(':')[0]] = i.split(':')[1]
    data = body_dict
    _LOGGER.info("xlbpay agent pay notify data: %s", data)
    xlbpay_notify(data, xlbpay_api_key(data['merchNo']))
    out_order_no = data['orderNo']
    pay_status = data['orderStatus']
    pay_fee = data['tradeAmt']
    xlbpay_handler.agent_pay_notify(out_order_no, pay_status, pay_fee)

    return HttpResponse('SUCCESS', status=200)
